<script setup lang="ts">
import { computed, onBeforeMount, ref, unref } from 'vue'
import { useBaseApi } from '@/api/base'
import { useRoute } from 'vue-router'
import mittBus from '@/utils/mitt'
import type { VxeTableEvents, VxeToolbarProps } from 'vxe-table'
import type {
  BusinessUIAction,
  BusinessUIFormType,
  BusinessUIQueryType,
  BusinessUITableType,
  DicType,
  WorkflowDesignRow
} from '@/types/custom'

import TemplateVxeGrid from '@/views/components/grid/components/TemplateVxeGrid.vue'

interface Props {
  disabled?: boolean
  params?: TypedAny
  insert?: boolean
  height?: number
  boxShadow?: boolean
  ready?: (value: number) => void
}

const route = useRoute()

const props = defineProps<Props>()

const emit = defineEmits(['fetch', 'close', 'radio-change'])

const modelValue = defineModel<string>()

const { get_business_ui } = useBaseApi()

// 加载
const loading = ref(false)
// 查询栏
const uiQuery = ref<BusinessUIQueryType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])
// 查询字典
const dicQuery = ref<DicType[]>([])
// 按钮配置
const uiActions = ref<BusinessUIAction[]>([])
// 关联流程
const wfDesign = ref<WorkflowDesignRow | undefined>()
// 表格
const gridRef = ref()
// 工具栏配置
const toolbarConfig = ref<VxeToolbarProps>({})

const emptyText = computed(() => {
  return uiTable.value?.default_value_parse.emptyText || '暂无数据'
})

/**
 * 初始化mitt事件
 */
const onEventMitt = () => {
  if (uiTable.value && ['sys_workflow_list', 'sys_user_msg'].includes(uiTable.value.id)) {
    mittBus.on('onUpdateMsg', () => {
      onFetch()
    })
  }
}

/**
 * 格式化默认参数
 */
const onDefaultFetch = async () => {
  const id = unref(modelValue)
  if (!id) return
  loading.value = true
  return get_business_ui(id, true)
    .then(({ data }) => {
      const dic_table = data.dic_table || []
      const dic_query = data.dic_query || []
      const ui_table = data.ui_table
      const ui_query = data.ui_query
      const ui_form = data.ui_form
      const ui_actions = props.disabled ? [] : data.actions || []
      const wf_design = data.wf_design
      if (ui_table) {
        const { default_value_parse } = ui_table
        if (default_value_parse.toolbarConfig)
          toolbarConfig.value = default_value_parse.toolbarConfig
      }
      if (ui_table) uiTable.value = ui_table
      if (ui_query) uiQuery.value = ui_query
      if (ui_form) uiForm.value = ui_form

      dicQuery.value = dic_query
      dicTable.value = dic_table
      wfDesign.value = wf_design
      uiActions.value = ui_actions
      onEventMitt()
    })
    .finally(() => (loading.value = false))
}

const onFetch = () => {
  gridRef.value?.onFetch()
}

/**
 * 单选
 */
const onRadioChange: VxeTableEvents.RadioChange<TypedAny> = (item) => {
  emit('radio-change', item)
}

onBeforeMount(() => {
  if (route.query.id) {
    modelValue.value = String(route.query.id)
  } else if (!modelValue.value) modelValue.value = String(route.meta.id)
  onDefaultFetch()
})

defineExpose({ onFetch, gridRef, uiTable })
</script>

<template>
  <TemplateVxeGrid
    ref="gridRef"
    v-model="loading"
    :params="params"
    :toolbar-config="toolbarConfig"
    :ui-form="uiForm"
    :ui-table="uiTable"
    :ui-query="uiQuery"
    :dic-query="dicQuery"
    :dic-table="dicTable"
    :ui-actions="uiActions"
    :wf-design="wfDesign"
    :box-shadow="boxShadow"
    :disabled="disabled"
    :insert="insert"
    :height="height"
    :ready="ready"
    :empty-text="emptyText"
    @close="emit('close', $event)"
    @fetch="emit('fetch', $event)"
    @radio-change="onRadioChange"
  />
</template>
